<?php

class champChooseTeam
{
	var $champ;
	var $teamOptions;
	var $mess;
	
	var $valid;

	function champChooseTeam($champ)
	{
		$this->champ = $champ;
		global $db, $lang;
		include_once('includes/addMessage.php');
		
		//are we logged in?
		if(isset($_SESSION['valid_id']))
		{
			$teamOptions = '';
			
			if($this->champ['c_multiDriverEntryMin'] == 0)
				$teamOptions .= '<option value="0">' . $lang['Independent'] . ' (' . $lang['AnyCar'] . ')</option>';
				
			$q = 'SELECT  t_id, t_name, ' .
					'(SELECT CONCAT(c_manufacturer," ", c_model) FROM ' . CHAMPSIGNUPS_TABLE . ', ' . CARS_TABLE . 
						' WHERE cs_driver = cs_entryOwner AND c_id = cs_car AND cs_team = t_id AND cs_champ = ' . $this->champ['c_id'] . ' LIMIT 0, 1) as t_car, ' .
					'(SELECT count(*) FROM ' . CHAMPSIGNUPS_TABLE . ' WHERE cs_driver = cs_entryOwner AND  cs_team = t_id AND cs_champ = ' . $this->champ['c_id'] . 
						' LIMIT 0, 1) as tm_entries ' .
					' FROM ' . TEAMMEMBERS_TABLE . ', ' . TEAMS_TABLE . 
					' WHERE (tm_team = t_id OR tm_team = t_parent) AND tm_approved = 1  AND tm_driver = ' . $_SESSION['valid_id'] . 
					' GROUP BY t_id ';

			$result = $db->sql_query($q);
			while($row = $db->sql_fetchrow($result)) 
			{
				if($this->champ['c_driversPerTeam'] <= 0 || $this->champ['c_driversPerTeam'] > $row['tm_entries'])
				{
					$car = $champ['c_multipleCarsPerTeam'] == 1 || $row['t_car'] == '' ? $lang['AnyCar'] : $row['t_car'];
					$teamOptions = $teamOptions . 
							'<option value="'.$row['t_id'].'">'  . stripslashes($row['t_name']) . ' (' . $car . ')</option>';
				}
			}
			
			$infomess = $lang['ChampSignupTeamInfo'] . '<br><br>';
			$infomess .= $lang['ChampionshipRulesIntroduction'] . '<br><br>';
			$infomess .= $champ['c_carChanging'] == 1 ? $lang['ChampionshipCarChangingYes'] . '<br>' : $lang['ChampionshipCarChangingNo'] . '<br>';
			$infomess .= $lang['ChampionshipTeamChangingOpt' .$champ['c_teamChanging']] . '<br>';
			$infomess .= $champ['c_multipleCarsPerTeam'] == 1 ? $lang['ChampionshipOneMakePerTeamNo'] . 
								'<br>' : $lang['ChampionshipOneMakePerTeamYes'] . '<br>';
			$infomess .= $champ['c_driversPerTeam'] > 0 ? str_replace('{numdrivers}',$champ['c_driversPerTeam'],$lang['ChampionshipDriversPerTeamYes'] . '<br>'):'';
			$infomess .= $champ['c_multiDriverEntryMin'] > 0 ? $lang['ChampionshipMultiDriverTeam']:'';
			
			$this->mess = new addMessage($infomess, $lang['ChampSignup'] );
			$this->teamOptions = $teamOptions;
			$this->valid = true;

		}
	}
	
	function render()
	{
		if($this->valid)
		{
			global $lang, $skin_dir;
			$teamOptions = $this->teamOptions;
			$nextEnabled = $teamOptions == '' ? 'DISABLED' : '';
			$champid = $this->champ['c_id'];
			$this->mess->render();
			include $skin_dir . 'tpl/champChooseTeam.tpl';
		}
	}
	

}


class champChooseDetails
{
	var $champ;
	var $carOptions = '';
	var $numberOptions = '';
	var $divisionID;
	var $divisionName;
	var $teamID;
	var $teamName;
	var $mess;
	
	var $valid;

	function champChooseDetails($champ, $teamid)
	{
		$this->champ = $champ;
		global $db, $lang;
		include_once('includes/addMessage.php');
		
		//are we logged in?
		if(isset($_SESSION['valid_id']))
		{
			$this->teamID = 0;
			$this->teamName = $lang['Independent'];
			$carname = '';
			$carid = 0;
			if($_POST['team'] > 0)
			{
				$q = 'SELECT  t_id, t_name, ' .
						'(SELECT CONCAT(c_manufacturer," ", c_model) FROM ' . CHAMPSIGNUPS_TABLE . ', ' . CARS_TABLE . 
							' WHERE cs_driver = cs_entryOwner AND c_id = cs_car AND cs_team = t_id AND cs_champ = ' . $this->champ['c_id'] . ' LIMIT 0, 1) as t_car, ' .
						'(SELECT c_id FROM ' . CHAMPSIGNUPS_TABLE . ', ' . CARS_TABLE . 
							' WHERE cs_driver = cs_entryOwner AND  c_id = cs_car AND cs_team = t_id AND cs_champ = ' . $this->champ['c_id'] . ' LIMIT 0, 1) as t_carid, ' .
						'(SELECT count(*) FROM ' . CHAMPSIGNUPS_TABLE . ' WHERE cs_driver = cs_entryOwner AND  cs_team = tm_team AND cs_champ = ' . $this->champ['c_id'] . 
							' LIMIT 0, 1) as tm_entries ' .
						' FROM ' . TEAMMEMBERS_TABLE . ', ' . TEAMS_TABLE . 
						' WHERE (tm_team = t_id OR tm_team = t_parent)  AND tm_approved = 1  AND t_id = ' . $_POST['team'];
				
				$result = $db->sql_query($q);
				if($row = $db->sql_fetchrow($result)) 
				{
					if($this->champ['c_driversPerTeam'] <= 0 || $this->champ['c_driversPerTeam'] > $row['tm_entries'])
					{
						$this->teamID = $row['t_id'];
						$this->teamName = $row['t_name'];
						if($row['t_carid'] != '' && $this->champ['c_multipleCarsPerTeam'] == 0)
						{
							$carid = $row['t_carid'];
							$car = $row['t_car'];
						}
					}
				}
			}
			
			//we can choose any valid car for the championship
			if($carid == 0)
			{
				 $q_cars = 'SELECT c.c_id, c.c_model, c.c_manufacturer, d_title
				 			FROM ' . CARS_TABLE . ' c, ' . CHAMP_CLASSES_TABLE . ' cl
							LEFT JOIN ' . DIVISIONS_TABLE . '
							ON cl.c_defaultdiv = d_id
							WHERE c.c_class = cl.c_class AND cl.c_champid = ' . $this->champ['c_id'] . '
							ORDER BY c_manufacturer, c_model';
				$result = $db->sql_query($q_cars);
				while($row = $db->sql_fetchrow($result)) 
				{
					$this->carOptions .= '<option value="' . $row['c_id'] . '">' . $row['c_manufacturer'] . ' ' . $row['c_model'] . 
										 ($row['d_title'] == '' ? '' : ' (' . $lang['ChampSignupDivision'] . ': ' . $row['d_title'] . ')') .
										 '</option>';
				}
			}
			else
			{
				$this->carOptions = '<option value="' . $carid . '">' . $car . '</option>';
			}
			
			//get custom default division details
			$q_div = 'SELECT d_title, d_id FROM ' . RESERVEDDIVISIONS_TABLE . ', ' . DIVISIONS_TABLE . 
					 	' WHERE d_id = r_division AND r_driver = ' . $_SESSION['valid_id'] . ' AND r_champ = ' .  $champ['c_id'] ;
			$result = $db->sql_query($q_div);
			if($row = $db->sql_fetchrow($result)) 
			{
				$this->divisionID = $row['d_id'];
				$this->divisionName = $row['d_title'];
			}
			else
			{
				//get championship default details
				$q_div = 'SELECT d_title, d_id FROM ' . DIVISIONS_TABLE . ' Where d_id = ' . $champ['c_defaultDiv'] .
						 ' AND d_champid =  ' .  $champ['c_id'] ;
				$result = $db->sql_query($q_div);
				if($row = $db->sql_fetchrow($result)) 
				{
					$this->divisionID = $row['d_id'];
					$this->divisionName = $row['d_title'];
				}
				else
				{
					$this->divisionID = 0;
					$this->divisionName = $lang['Unassigned'];
				}
			}
			
			//do i have a number reserved for me?
			$q_myreserved = 'SELECT r_no FROM ' . RESERVEDNUMBERS_TABLE . ' WHERE r_driver = ' . $_SESSION['valid_id'] .
								' AND r_champ = ' . $this->champ['c_id'];
			$result = $db->sql_query($q_myreserved);
			$mynumber = 0;
			if($row = $db->sql_fetchrow($result))
			{
				$mynumber = $row['r_no'];
			}
			
			$this->numberOptions = '';
			$q_numbers = 'SELECT car_no FROM ' . CARNUMBERS_TABLE . ' WHERE car_no NOT IN ' .
				'(SELECT cs_no FROM ' . CHAMPSIGNUPS_TABLE . ' WHERE cs_champ = ' . $this->champ['c_id'] . ') AND car_no NOT IN' .
				'(SELECT r_no FROM ' . RESERVEDNUMBERS_TABLE . ' WHERE r_driver != ' . $_SESSION['valid_id'] .' AND r_champ = ' . 
							$this->champ['c_id'] . ') ORDER BY car_no';

			$result = $db->sql_query($q_numbers);
			while($row = $db->sql_fetchrow($result)) 
			{
				if($mynumber == $row['car_no'])
				{
					$this->numberOptions = $this->numberOptions . 
						'<option value="'.$row['car_no'].'" SELECTED>'  . $row['car_no'] . ' (R)</option>';
				}
				else
				{
					$this->numberOptions = $this->numberOptions . 
						'<option value="'.$row['car_no'].'">'  . $row['car_no'] . '</option>';
				}
			}
			
			$this->mess = new addMessage($lang['ChampSignupDetailsInfo'], $lang['ChampSignup'] );
			$this->valid = true;

		}
	}
	
	function render()
	{
		if($this->valid)
		{
			global $lang, $skin_dir;
			$remNumStart = $this->champ['c_carNumbers'] == 1 ? '' : '<input name="number" type="hidden" value="0"><!--';
			$remNumEnd = $this->champ['c_carNumbers'] == 1 ? '' : '-->';
			$carOptions = $this->carOptions;
			$numberOptions = $this->numberOptions;
			$divisionID = $this->divisionID;
			$divisionName = $this->divisionName;
			$teamID = $this->teamID;
			$teamName = $this->teamName;
			$champid = $this->champ['c_id'];
			$this->mess->render();
			include $skin_dir . 'tpl/champChooseDetails.tpl';
		}
	}
	

}


class championshipSignup
{
	var $champ;
	var $items = Array();

	function championshipSignup($champ)
	{
		$this->champ = $champ;
		global $db, $lang;
		include_once('includes/addMessage.php');
		
		//are we logged in?
		if(isset($_SESSION['valid_id']))
		{
			//signups not open
			if($this->champ['c_openSignUps'] == 0)
			{
				$this->items[] = new addMessage($lang['ChampSingupsClosed'], $lang['ChampSingupsClosedTitle']);
			}
			//already signed up or choose details
			else if(isset($_POST['submitTeam'])&& isset($_POST['team']))
			{
				$q = 'SELECT * FROM ' . CHAMPSIGNUPS_TABLE . ' WHERE cs_driver = ' . $_SESSION['valid_id'] . ' AND cs_champ = ' . $this->champ['c_id'] ;
				$result = $db->sql_query($q);
				if($row = $db->sql_fetchrow($result)) 
				{
					$this->items[] = new addMessage(str_replace('{id}', $this->champ['c_id'], $lang['ChampAlreadySignedUp']), 
													$lang['ChampAlreadySignedUpTitle'], false, true);
				}
				else
				{
					$this->items[] = new champChooseDetails($this->champ, $_POST['team']);
				}
			}
			//add entry
			else if(isset($_POST['addRecord'])&& isset($_POST['champ']) && isset($_POST['team']) && isset($_POST['division'])
							&& isset($_POST['number'])&& isset($_POST['car'])&& $_POST['champ'] == $this->champ['c_id'])
			{
				$valid=true;
				
				//check we havent filled our quota
				$q = 'SELECT ' .
					'(SELECT count(*) FROM ' . CHAMPSIGNUPS_TABLE . ' WHERE cs_driver = cs_entryOwner AND cs_champ = ' . $this->champ['c_id'] . ') AS entries, ' .
					'(SELECT sum(d_signuplimit) FROM ' . DIVISIONS_TABLE . ' WHERE d_champid = ' . $this->champ['c_id'] . ') AS max';
				$result = $db->sql_query($q);
				if($row = $db->sql_fetchrow($result)) 
				{
					if($row['entries'] >= $row['max'])
					{
						$this->items[] = new addMessage($lang['ChampSignupMaxEntries'], $lang['ErrorTitle'], false, true);
						$valid = false;	
					}
					else
					{
						if($champ['c_openSignUps'] == 0)
						{
							$valid = false;
							$this->items[] = new addMessage($lang['ChampSingupsClosed'], $lang['ErrorTitle'], false, true);
						}
						else
						{
							//check the car number
							$q = 'SELECT cs_no FROM ' . CHAMPSIGNUPS_TABLE . ' WHERE cs_no = ' . $_POST['number'] . ' AND cs_champ = ' . $_POST['champ'];
							$result = $db->sql_query($q);
							if($_POST['number'] > 0 && $row = $db->sql_fetchrow($result)) 
							{
								$this->items[] = new addMessage($lang['ChampSignupNumberInUse'], $lang['ErrorTitle'], false, true);
								$valid=false;
							}
							else
							{
								if($_POST['team'] > 0)
								{
									$q = 'SELECT  t_id, t_name, ' .
											'(SELECT c_id FROM ' . CHAMPSIGNUPS_TABLE . ', ' . CARS_TABLE . 
												' WHERE c_id = cs_car AND cs_team = tm_team AND cs_champ = ' . $this->champ['c_id'] .
												 ' LIMIT 0, 1) as t_carid, ' .
											'(SELECT count(*) FROM ' . CHAMPSIGNUPS_TABLE . ' WHERE cs_team = tm_team AND cs_champ = ' . 
												$this->champ['c_id'] . ' LIMIT 0, 1) as tm_entries ' .
											' FROM ' . TEAMMEMBERS_TABLE . ', ' . TEAMS_TABLE . 
											' WHERE (tm_team = t_id OR tm_team = t_parent) AND tm_approved = 1  AND tm_team = ' . $_POST['team'] . 
											' GROUP BY t_id ';
						
									$result = $db->sql_query($q);
									if($row = $db->sql_fetchrow($result)) 
									{
										if($this->champ['c_driversPerTeam'] > 0 && $this->champ['c_driversPerTeam'] <= $row['tm_entries'])
										{
											$this->items[] = new addMessage($lang['ChampSignupFullTeam'], $lang['ErrorTitle'], false, true);
											$valid = false;	
										}
										else if($this->champ['c_multipleCarsPerTeam'] == 0 && $row['t_carid'] != '' && $row['t_carid'] != $_POST['car'])
										{
											$this->items[] = new addMessage($lang['ChampSignupWrongCar'], $lang['ErrorTitle'], false, true);
											$valid = false;	
										}
									}
								}
							}
						}
					}
				}
				else
				{
					$this->items[] = new addMessage($lang['DatabaseError'], $lang['ErrorTitle'], false, true);
					$valid = false;	
				}
				
				
				
				
				if($valid)
				{
					//Check Division Value
					$q = 'SELECT cl.c_defaultdiv 
						  FROM ' . CHAMP_CLASSES_TABLE . ' cl, ' . CARS_TABLE . ' c
						  WHERE c.c_class = cl.c_class AND c.c_id = ' . $_POST['car'] . ' AND cl.c_champid = ' . $this->champ['c_id'];
					$result = $db->sql_query($q);
					if($row = $db->sql_fetchrow($result)) 
					{
						if($row['c_defaultdiv'] > 0)
							$_POST['division'] = $row['c_defaultdiv'];
					}	  
					
					$q = 'INSERT INTO ' . CHAMPSIGNUPS_TABLE . ' (cs_no, cs_driver, cs_team, cs_champ, cs_div, cs_image, cs_car, cs_imageThmb, cs_entryOwner)
						  VALUES (' . $_POST['number'] . ', ' . $_SESSION['valid_id'] . ', ' . $_POST['team'] . ', ' . $this->champ['c_id'] . ', ' . 
						  			  $_POST['division'] . ', "", ' . $_POST['car'] . ', "", ' . $_SESSION['valid_id'] . ')';
					$db->sql_query($q);
					if($db->sql_affectedrows() == 1)
					{
						//delete any unused reserved numbers
						$q = 'DELETE FROM ' . RESERVEDNUMBERS_TABLE . ' WHERE r_no != ' . $_POST['number'] . ' AND r_driver = ' . 
								$_SESSION['valid_id'] . ' AND r_champ = ' . $this->champ['c_id'];
						$db->sql_query($q);
						$this->items[] = new addMessage(str_replace('{id}', $this->champ['c_id'], $lang['ChampSignedUp']), 
														$lang['ChampSignedUpTitle'], false, true);
					}
				}
			}
			//see if we can signup
			else
			{
				$q = 'SELECT * FROM ' . CHAMPSIGNUPS_TABLE . ' WHERE cs_driver = ' . $_SESSION['valid_id'] . ' AND cs_champ = ' . $this->champ['c_id'] ;
				$result = $db->sql_query($q);
				if($row = $db->sql_fetchrow($result)) 
				{
					$this->items[] = new addMessage(str_replace('{id}', $this->champ['c_id'], $lang['ChampAlreadySignedUp']), 
													$lang['ChampAlreadySignedUpTitle'], false, true);
				}
				else
				{
					//check we havent filled our quota
					$q = 'SELECT 
						 (SELECT count(*) FROM ' . CHAMPSIGNUPS_TABLE . ' WHERE cs_driver = cs_entryOwner AND cs_champ = c_id) AS entries, 
						 (SELECT sum(d_signuplimit) FROM ' . DIVISIONS_TABLE . ' WHERE d_champid = c_id) AS max,
						 (SELECT COUNT(*) FROM ' . RACERESULTS_TABLE . ' WHERE r_driver = u_id) as races,
       					 (SELECT b_id FROM ' . BANS_TABLE . ' WHERE b_user = u_id AND b_startDate < NOW() AND b_endDate > NOW() AND (b_license = cl.l_id OR b_license = 0)) as banned,
					       cl.l_order AS cl_order, cl.l_name as cl_name, ul.l_order as ul_order, ul.l_name as ul_name
						 FROM ' . CHAMPIONSHIPS_TABLE . ', ' . LICENSES_TABLE . ' ul, ' . LICENSES_TABLE . ' cl, ' . LCUSERS_TABLE . '
						 WHERE u_license = ul.l_id AND u_id = ' . $_SESSION['valid_id'] . ' AND c_id = ' . $this->champ['c_id'] . ' AND c_license = cl.l_id';
					$result = $db->sql_query($q);
					if($row = $db->sql_fetchrow($result)) 
					{
						if($row['banned'] != '')
						{
							$this->items[] = new addMessage(sprintf($lang['ChampSignedUpBanned'], 
												 $_SESSION['valid_id']), $lang['ErrorTitle'], false, true);
						}
						if($row['ul_order'] > $row['cl_order'] )
						{
							$this->items[] = new addMessage(sprintf($lang['ChampSignedInvalidLicense'], 
												$row['ul_name'], $row['cl_name'], $_SESSION['valid_id']), $lang['ErrorTitle'], false, true);
						}
						else if($row['entries'] >= $row['max'])
						{
							$this->items[] = new addMessage($lang['ChampSignupMaxEntries'], $lang['ErrorTitle'], false, true);
						}
						else if($this->champ['c_minRacesToEnter'] > $row['races'])
						{
							$this->items[] = new addMessage(sprintf($lang['ChampionshipMinRacesToEnterError'], 
								$this->champ['c_minRacesToEnter'], $row['races']), $lang['ErrorTitle'], false, true);
						} 
						else
						{
							$this->items[] = new champChooseTeam($this->champ);
						}
					}
					else
					{
						$this->items[] = new addMessage($lang['DatabaseError'], $lang['ErrorTitle'], false, true);
					}
				}
			}
		}
	}
	
	function render()
	{
		foreach($this->items as $value)
		{
			$value->render();
		}
	}
	

}

?>